import {
  Injectable,
  InternalServerErrorException,
  BadRequestException,
} from '@nestjs/common';
import { PrismaService } from 'src/services/prisma.service';
import { article_tag } from '@prisma/client';
import type { Tag } from 'src/typing';

@Injectable()
export class ArticleTagService {
  constructor(private readonly prisma: PrismaService) {}
  async findAll(article_id: number): Promise<[article_tag[], number]> {
    const [list, total] = await Promise.all([
      this.prisma.article_tag.findMany({
        where: {
          article_id,
        },
      }),
      this.prisma.article_tag.count({
        where: {
          article_id,
        },
      }),
    ]);
    return [list, total];
  }

  findOne(article_id: number, tag_id: number): Promise<article_tag | null> {
    return this.prisma.article_tag.findUnique({
      where: {
        article_id_tag_id: {
          article_id,
          tag_id,
        },
      },
    });
  }

  /**
   * 根据 article_tag_id 删除标签
   *
   * @param {number} article_tag_id - 文章标签ID
   */
  deleteOneTag(article_tag_id: number): Promise<article_tag> {
    try {
      return this.prisma.article_tag.delete({
        where: {
          article_tag_id,
        },
      });
    } catch (error) {
      throw new InternalServerErrorException('删除失败');
    }
  }

  /**
   * 根据 article_id 删除文章所有标签
   *
   * @param {number} article_id - 文章ID
   */
  deleteArticleAllTag(article_id: number): Promise<{ count: number }> {
    return this.prisma.article_tag.deleteMany({
      where: {
        article_id,
      },
    });
  }

  /**
   * 给文章添加标签
   * 每个文章不能超过3个标签
   *
   * @param {Object} info - 文章添加标签的详细信息
   * @param {number} info.article_id - 文章ID
   * @param {number[]} info.tags - 标签ID数组，最多包含3个标签
   * @throws  {Error} - 如果标签数超过3个或发生其他操作失败时，抛出对应错误
   */
  async articleAddTag(info: {
    article_id: number;
    tags: Tag[];
  }): Promise<{ count: number }> {
    const articleTagData = info.tags.map((tag) => ({
      article_id: info.article_id,
      tag_id: tag.tag_id,
      tag_name: tag.tag_name,
    }));
    // 去掉原来文章的标签
    await this.deleteArticleAllTag(info.article_id);
    try {
      return this.prisma.article_tag.createMany({
        data: articleTagData,
      });
    } catch (error) {
      throw new BadRequestException('添加标签失败');
    }
  }
}
